<div style="overflow-y:auto;height: 650px">
    <form id="paperRecord-form" lay-filter="paperRecord-form" class="layui-form model-form layui-form-pane"
          style="margin-left: 50px">
        <div style="display: flex;justify-content: center;flex-direction: column;margin: 20px 0;text-align: center">
            <div style="font-size: 30px;font-weight: bold;margin-top: -30px" id="ptitle"></div>
            <div style="margin: 20px 0">问卷说明:<span id="instru"></span></div>
            <div style="font-size: 14px;color: black;font-weight: bold">截止日期:<span id="endtim"></span></div>
        </div>
        <!--单选题-->
        <div id="question-option"></div>
        <!--评分-->
        <div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">综合评分<span class="layui-badge-dot"></span></label>
                <div id="rate-type">
                </div>
            </div>
        </div>
        <!--建议-->
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">您的建议</label>
            <div class="layui-input-block">
                <textarea placeholder="请输入内容" class="layui-textarea" id="suggestion"></textarea>
            </div>
        </div>
        <div class="layui-form-item model-form-footer">
            <button class="layui-btn" lay-filter="paperRecord-form-submit" lay-submit>保存</button>
            <button class="layui-btn layui-btn-primary" ew-event="closeDialog" type="button">关闭</button>
        </div>
    </form>
</div>
<script>
    layui.use(['config', 'layer', 'admin', 'form', 'rate', 'slider', 'tinymce'], function () {
        let layer = layui.layer;
        let admin = layui.admin;
        let form = layui.form;
        let config = layui.config;
        let rate = layui.rate;
        let slider = layui.slider;
        let tinymce = layui.tinymce;

        let paper = admin.getTempData('t_showPaper');
        getRateCode(paper.rtcode);

        let paperInfo = null;
        admin.req('api-paper/paper/findById/' + paper.papeid, {}, function (result) {
            paperInfo = result.data;
        }, 'GET');

        //获取当前登录用户
        let loginUser = config.getUser();

        let paperData = {};//用于存储问卷数据

        //获取问卷
        layer.load(2);
        admin.req('api-paper/paper/getQuestionAndOption/' + paper.papeid, {}, function (result) {
            layer.closeAll('loading');
            $('#ptitle').html(paper.ptitle);
            $('#instru').html(paper.instru);
            $('#endtim').html(paper.endtim);
            getQuestionAndOption(result.data);
            paperData = result.data;
        }, 'GET');

        //获取问卷详情信息
        layer.load(2);
        admin.req('api-paper/paper/findPaperInfo?papeid=' + paper.papeid + '&userid=' + loginUser.id, {}, function (result) {
            layer.closeAll('loading');
            setPaperInfo(result.data);
        }, 'GET');

        let starScore = $("input[name='star-score']").val();
        let slideScore = $("input[name='slide-score']").val();
        //星数
        rate.render({
            elem: '#star-score'
            , value: starScore
            , text: true
            , setText: function (value) { //自定义文本的回调
                let arrs = {
                    '0': '请打分'
                    , '1': '不及格'
                    , '2': '继续努力'
                    , '3': '中等'
                    , '4': '良好'
                    , '5': '优秀'
                };
                this.span.text(arrs[value] || (value + "星"));
                $("input[name='star-score']").val(value);
            }
        });

        //滑块
        slider.render({
            elem: '#slide-score'
            , input: true
            , theme: '#1E9FFF'
            , value: slideScore
            , min: 0
            , setTips: function (value) {
                $("input[name='slide-score']").val(value);
            }
        });

        //富文本
        tinymce.render({
            elem: "#suggestion"
            , height: 400
            , toolbar: ['undo | redo | removeformat | bold | italic | underline | strikethrough | alignleft ' +
            '| aligncenter | alignright | alignjustify | subscript | superscript ' +
            '| bullist | numlist | outdent | indent | blockquote | cut | copy | paste']
            , menubar: false //隐藏菜单栏
            // 支持tinymce所有配置
        }, (opt, edit) => {
            // 加载完成后回调 opt 是传入的所有参数
            // edit是当前编辑器实例，等同于t.get返回值
        });

        function getRateCode(rtcode) {
            if (rtcode === 'cent') {  //百分制
                scoreCent();
            } else if (rtcode === 'star') {//星数
                scoreStar();
            } else if (rtcode === 'level') {//等级制
                scoreLevel();
            }
        }

        /**
         *  获取问题以及选项
         */
        function getQuestionAndOption(data) {
            let html = '';
            for (let i = 0; i < data.length; i++) {
                html += '<div class="layui-form-item layui-form-text">\n' +
                    '       <label class="layui-form-label">' + (i + 1) + '.' + data[i].qtitle + '<span class="layui-badge-dot"></span></label>\n' +
                    '       <div class="layui-input-block">'
                ;
                for (let j = 0; j < data[i].optionList.length; j++) {
                    html += '<input type="radio" name="quoption' + i + '" value="' + data[i].optionList[j].optnid + '" title="' + data[i].optionList[j].opname + '" ' +
                        'lay-verify="otherReq"/>';
                }
                html += '    </div>\n          </div>';
            }

            $('#question-option').html(html);
            form.render('radio');
        }


        /**
         *  百分制
         */
        function scoreCent() {
            let html = `<div style="margin: 20px 0">
                          <div style="font-size: 10px;color: gray;margin-bottom: 20px">
                              说明:【0-60/60-70/70-80/80-90/90-100/】分别对应【不及格/继续努力/中等/良好/优秀】
                          </div>
                          <input name="slide-score" hidden>
                          <div id="slide-score" class="demo-slider"></div>
                      </div>`;
            $('#rate-type').html(html);
        }

        /**
         * 星数
         */
        function scoreStar() {
            let html = `<div style="margin-top: 10px">
                        <div style="font-size: 10px;color: gray">说明:【1/2/3/4/5星】分别对应【不及格/继续努力/中等/良好/优秀】</div>
                        <input name="star-score" hidden/>
                        <div id="star-score"></div>
                    </div>`;
            $('#rate-type').html(html);
        }

        /**
         * 等级制
         */
        function scoreLevel() {
            let html = `<div style="margin-top: 20px">
                          <div style="font-size: 10px;color: gray">说明:【A/B/C/D/E】分别对应【优秀/良好/中等/继续努力/不及格】</div>
                          <input type="radio" name="levelScore" lay-verify="otherReq" value="A" title="A"/>
                          <input type="radio" name="levelScore" lay-verify="otherReq" value="B" title="B"/>
                          <input type="radio" name="levelScore" lay-verify="otherReq" value="C" title="C"/>
                          <input type="radio" name="levelScore" lay-verify="otherReq" value="D" title="D"/>
                          <input type="radio" name="levelScore" lay-verify="otherReq" value="E" title="E"/>
                      </div>`;
            $('#rate-type').html(html);
            form.render();
        }

        /**
         * 赋值
         * @param data
         */
        function setPaperInfo(data) {
            for (let i = 0; i < data.optnids.length; i++) {
                $('input[name="quoption' + i + '"][value=' + data.optnids[i] + ']').next().click();
            }
            $("input[name='star-score']").val(data.pscore);
            $("input[name='slide-score']").val(data.pscore);
            $('input[name="levelScore"][value=' + data.pscore + ']').next().click();
            $('#suggestion').html(data.contex);
        }

        form.render();

        // 表单提交事件
        form.on('submit(paperRecord-form-submit)', function (data) {
            let userId = loginUser.id;
            let paperId = paper.papeid;
            let respdt = paperInfo.respdt;
            let contex = tinymce.get('#suggestion').getContent();
            //被建议人
            let sugper = paper.facegp;
            //问题ids
            let questionIds = [];
            for (let i = 0; i < paperData.length; i++) {
                questionIds.push(paperData[i].quesid);
            }
            //选项ids
            let optionIds = [];
            for (let j = 0; j < paperData.length; j++) {
                optionIds.push($('input[name="quoption' + j + '"]:checked').val());
            }
            //分数
            let pscore = null;
            let slideScore = $("input[name='slide-score']").val();
            let starScore = $("input[name='star-score']").val();
            let levelScore = $("input[name='levelScore']:checked").val();
            if (slideScore !== undefined && slideScore !== '' && slideScore !== null) {
                pscore = slideScore;
            }
            if (starScore !== undefined && starScore !== '' && starScore !== null) {
                pscore = starScore;
            }
            if (levelScore !== undefined && levelScore !== '' && levelScore !== null) {
                pscore = levelScore;
            }

            let params = {
                papeid: paperId,
                userid: userId,
                quesids: questionIds,
                optnids: optionIds,
                pscore: pscore,
                contex: contex,
                sugper: sugper,
                respdt: respdt
            };
            layer.load(2);
            admin.req('api-paper/paper/updatePaperData', JSON.stringify(params), function (data) {
                layer.closeAll('loading');
                if (data.code === 0) {
                    layer.msg(data.msg, {icon: 1, time: 500});
                    admin.finishPopupCenter();
                } else {
                    layer.msg(data.msg, {icon: 2, time: 500});
                }
            }, 'post');
            return false;
        });

        //自定义验证规则
        form.verify({
            otherReq: function (value, item) {
                let $ = layui.$;
                let verifyName = $(item).attr('name')
                    , verifyType = $(item).attr('type')
                    , formElem = $(item).parents('.layui-form')//获取当前所在的form元素，如果存在的话
                    , verifyElem = formElem.find('input[name=' + verifyName + ']')//获取需要校验的元素
                    , isTrue = verifyElem.is(':checked')//是否命中校验
                    , focusElem = verifyElem.next().find('i.layui-icon');//焦点元素
                if (!isTrue || !value) {
                    //定位焦点
                    focusElem.css(verifyType === 'radio' ? {"color": "#FF5722"} : {"border-color": "#FF5722"});
                    //对非输入框设置焦点
                    focusElem.first().attr("tabIndex", "1").css("outline", "0").blur(function () {
                        focusElem.css(verifyType === 'radio' ? {"color": ""} : {"border-color": ""});
                    }).focus();
                    return '必填项不能为空';
                }
            }
        });

    });
</script>
